package app.myproject;

//file Serve.java  
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

public class ServeServlet extends HttpServlet {
	
	private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

	private DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
	
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {

		String cmd = req.getParameter("cmd");
		String key = req.getParameter("blob-key");
		
		Query query = new Query("__BlobInfo__"); 
	     
	    PreparedQuery pq = datastoreService.prepare(query); 
	    List<Entity> list = pq.asList(FetchOptions.Builder.withLimit(10));
	    Iterator<Entity> iter = list.iterator();
	    while (iter.hasNext()) {
	    	Entity item = (Entity) iter.next();
	    	String blobKeyString = item.getKey().getName();
	    	if ("list".equals(cmd)) {
	    		res.getWriter().println("<a href='serve?cmd=download&blob-key="+blobKeyString + "'>" + " " + String.valueOf(item.getProperty("filename")) +"</a><br/>");
	    	}
	    	else if ("delete".equals(cmd)) {
	    		BlobKey blobkey = new BlobKey(blobKeyString);
	    		blobstoreService.delete(blobkey);
	    		res.getWriter().println(blobKeyString + " deleted<br/>");
	    	}
	    	else if ("download".equals(cmd)) {
	    		if (key != null && key.length() > 0) {
	    			BlobKey blobKey = new BlobKey(key);
					blobstoreService.serve(blobKey, res);
	    		}
	    	}
	    	else {
	    		if (blobKeyString.equals(key)) {
	    			res.getWriter().println(blobKeyString + " existed.<br/>");
	    		}
	    	}
	    }

//		Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
//		Iterator<String> iter1 = blobs.keySet().iterator();
//		while (iter1.hasNext()) {
//			String key = iter1.next();
//			res.getWriter().println("+" + key + "<br/>");
//			List<BlobKey> list = blobs.get(key);
//			Iterator<BlobKey> iter2 = list.iterator();
//			while (iter2.hasNext()) {
//				BlobKey blobKey = iter2.next();
//				res.getWriter().println("-> " + blobKey.getKeyString() + "<br/>");
//			}
//		}

	}
}